package com.ruoyi.report.controller;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hig.onlineexam.domain.ExamUserScore;
import com.hig.onlineexam.domain.dto.LatestExamScore;
import com.hig.onlineexam.mapper.ExamUserScoreMapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.disk.domain.DiskFile;
import com.ruoyi.disk.mapper.DiskFileMapper;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.oiltank.domain.OilTank;
import com.ruoyi.oiltank.mapper.OilTankMapper;
import com.ruoyi.onway.domain.ReportOnway;
import com.ruoyi.onway.mapper.ReportOnwayMapper;
import com.ruoyi.report.domain.*;
import com.ruoyi.report.dto.DataObj;
import com.ruoyi.report.dto.FileGroupDTO;
import com.ruoyi.report.dto.ReportDataDTO;
import com.ruoyi.report.mapper.*;
import com.ruoyi.station.domain.ReportGasStation;
import com.ruoyi.station.mapper.ReportGasStationMapper;
import com.ruoyi.studylog.domain.TodayStudyLog;
import com.ruoyi.studylog.mapper.UserStudyLogMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.checkerframework.checker.units.qual.A;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.report.service.IReportPlanService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;

/**
 * 采购计划Controller
 *
 * @author ruoyi
 * @date 2024-10-12
 */
@RestController
@RequestMapping("/plan/plan")
@Api("采购计划相关")
public class ReportPlanController extends BaseController {
    @Autowired
    private IReportPlanService reportPlanService;
    @Autowired
    private ReportOnwayMapper reportOnwayMapper;
    @Autowired
    private ReportRefineryInfoMapper refineryInfoMapper;

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ExamUserScoreMapper userScoreMapper;
    @Autowired
    private DiskFileMapper diskFileMapper;

    /**
     * 查询采购计划列表
     */
    @PreAuthorize("@ss.hasPermi('plan:plan:list')")
    @GetMapping("/list")
    public TableDataInfo list(ReportPlan reportPlan) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 分页查询
        startPage();
        List<ReportPlan> list = reportPlanService.selectReportPlanList(reportPlan);

        // 遍历每个 ReportPlan

        for (ReportPlan plan : list) {
            Long id = plan.getId();
            // 查询 planId 对应的在途油信息
            ReportOnway reportOnway = new ReportOnway();
            reportOnway.setPlanId(id);
            List<ReportOnway> reportOnways = reportOnwayMapper.selectReportOnwayList(reportOnway);

            // 按 refineryId 对 ReportOnway 进行分组
            Map<Long, List<ReportOnway>> longListMap = this.groupByRefineryId(reportOnways);

            // 用 StringBuilder 替代 String 数组以便拼接消息
            StringBuilder msg = new StringBuilder();

            // 遍历分组，生成汇总消息
            longListMap.forEach((refineryId, reportList) -> {
                ReportRefineryInfo reportRefineryInfo = refineryInfoMapper.selectReportRefineryInfoById(refineryId);

                int i = 1;
                for (ReportOnway onway : reportList) {
                    msg.append(reportRefineryInfo.getRefineryName())
                            .append(" 第" + i + "批次于" + dateFormat.format(onway.getStartTime()) + "发了" + onway.getSendCarCount() + "车;" + onway.getSendWeight()
                                    + "吨;预计" + dateFormat.format(onway.getArriveTime()) + "时间到达。");
                    i++;

                }
                // 拼接汇总消息
            });
            plan.setExtra2(msg.toString());
        }

        // 返回表格数据
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('plan:plan:list')")
    @GetMapping("/listInfo")
    public TableDataInfo listInfo(ReportPlan reportPlan) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 分页查询
        startPage();
        List<ReportPlanInfo> list = reportPlanService.selectReportPlanListInfo(reportPlan);

        // 返回表格数据
        return getDataTable(list);
    }

    public Map<Long, List<ReportOnway>> groupByRefineryId(List<ReportOnway> reportOnways) {
        Map<Long, List<ReportOnway>> groupedByRefineryId = reportOnways.stream()
                .collect(Collectors.groupingBy(ReportOnway::getRefineryId));

        return groupedByRefineryId;
    }

    @GetMapping("/listNoPage")
    public TableDataInfo listNoPage(ReportPlan reportPlan) {

        List<ReportPlan> list = reportPlanService.selectReportPlanList(new ReportPlan());
        return getDataTable(list);
    }

    @GetMapping("7days")
    public AjaxResult query7days() {
        AllDTO allDTO = new AllDTO();
        DaysDTO lasaData = reportPlanService.queryLasa7days();
        DaysDTO aliData = reportPlanService.queryAli7days();
        DaysDTO linzhiData = reportPlanService.queryLinzhi7days();
        DaysDTO rikazeData = reportPlanService.queryRikaze7days();
        DaysDTO peisong = reportPlanService.queryPeisong7days();
        allDTO.setLasa(lasaData);
        allDTO.setRikaze(rikazeData);
        allDTO.setAli(aliData);
        allDTO.setLinzhi(linzhiData);
        return AjaxResult.success(allDTO);




    }

    @Autowired
    private OilTankMapper oilTankMapper;
    @Autowired
    private TokenService tokenService;

    @ApiOperation("报表")
    @GetMapping("report")
    public AjaxResult report(@RequestParam(required = false) String date) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        Long userId = user.getUserId();

        Long deptId = user.getDeptId();
        HashMap<Object, Object> map = new HashMap<>();

        AllDTO allDTO = new AllDTO();
        DaysDTO lasaData = reportPlanService.queryLasa7days();
        DaysDTO aliData = reportPlanService.queryAli7days();
        DaysDTO linzhiData = reportPlanService.queryLinzhi7days();
        DaysDTO rikazeData = reportPlanService.queryRikaze7days();
        DaysDTO peisong = reportPlanService.queryPeisong7days();
        allDTO.setLasa(lasaData);
        allDTO.setRikaze(rikazeData);
        allDTO.setAli(aliData);
        allDTO.setLinzhi(linzhiData);
//        allDTO.setPeisong(peisong);
        ReportPlan reportPlan = new ReportPlan();

        LocalDate currentDate = LocalDate.now().minusDays(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月");

        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        String formattedDate = currentDate.format(formatter);
        if (StringUtils.isEmpty(date)) {
             date =  LocalDate.now().format(fmt);
        }

        reportPlan.setExtra1(formattedDate);
        List<ReportPlanInfo> list = reportPlanService.selectReportPlanListInfo(reportPlan);
        OilTank oilTank = new OilTank();
//        if (!user.isAdmin()) {
//            oilTank.setDeptId(deptId);
//        }
        // 无数据过滤
        List<OilTank> oilTanks = oilTankMapper.selectOilTankListAll(oilTank);
        // 使用 Stream 过滤
        oilTanks = oilTanks.stream()
                .filter(tank -> tank.getDeptId()!=110L)
                .collect(Collectors.toList());
        map.put("7days", allDTO);
        map.put("plan", list);
        map.put("tanks", oilTanks);
        ReportDataDTO lasa = reportPlanService.queryLasaDaily(date);


        ReportDataDTO linzhi = reportPlanService.queryLinzhiDaily(date);
        ReportDataDTO rikaze = reportPlanService.queryRikazeDaily(date);
        ReportDataDTO ali = reportPlanService.queryAliDaily(date);
        ReportDataDTO peisongzhongxin = reportPlanService.queryPeisongzhongxinDaily(date);
        HashMap<Object, Object> dailyMap = new HashMap<>();
        HashMap<Object, Object> daily = new HashMap<>();
        dailyMap.put("lasa", lasa);
        dailyMap.put("linzhi", linzhi);
        dailyMap.put("rikaze", rikaze);
        dailyMap.put("ali", ali);
        dailyMap.put("peisongzhongxin", peisongzhongxin);
        map.put("daily", dailyMap);
        Gson gson = new Gson();
        System.out.println(map);
        return AjaxResult.success(map);
    }

    @Autowired
    private ReportDcMapper reportDcMapper;
    @Autowired
    private ReportScMapper reportScMapper;

    @Autowired
    private ReportOilDepotMapper depotMapper;
    @Autowired
    private ReportGasStationMapper stationMapper;
    @Autowired
    private UserStudyLogMapper userStudyLogMapper;
    @Autowired
    private ReportCarInfoMapper reportCarInfoMapper;




    @ApiOperation("screen")
    @GetMapping("screen")
    public AjaxResult screen() {
        List<SysUser> sysUsers = userMapper.selectUserList(new SysUser());
        Type userType = new TypeToken<List<Long>>() {}.getType();
        Gson gson = new Gson();
        List<ReportCarInfo> cars = reportCarInfoMapper.selectReportCarInfoList(new ReportCarInfo());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        ReportPlan reportPlan = new ReportPlan();

        LocalDate currentDate = LocalDate.now();
        LocalDate yesterday = LocalDate.now().minusDays(1);
        LocalDate day7before = LocalDate.now().minusDays(7);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月");
        DateTimeFormatter formatterScreen = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDate = currentDate.format(formatter);
        String formattedDateYesterday = yesterday.format(formatterScreen);
        String formattedDate7day = day7before.format(formatterScreen);
        reportPlan.setExtra1(formattedDate);
        List<ReportPlanInfo> list = reportPlanService.selectReportPlanListInfo(reportPlan);
        DataObj dataObj = new DataObj();
        DataObj.MonthlyPurchasePlan monthlyPurchasePlan = new DataObj.MonthlyPurchasePlan();
        monthlyPurchasePlan.setTableData(Collections.singletonList(list));
        dataObj.setMonthlyPurchasePlan(monthlyPurchasePlan);




        ReportDc reportDc = new ReportDc();
        reportDc.setName(formattedDateYesterday);

        List<ReportDc> reportDcs = reportDcMapper.selectReportDcList(reportDc);
        reportDcs= CollectionUtil.isNotEmpty(reportDcs)?Collections.singletonList(reportDcs.get(0)):new ArrayList<>();
        DataObj.XizangDistributionCenter xizangDistributionCenter = new DataObj.XizangDistributionCenter();
        reportDc.setName(null);
        reportDc.setStart(formattedDate7day);
        reportDc.setEnd(formattedDate);
        String maxDc = reportDcMapper.maxName();
        List<ReportDc> chartDatesDc = reportDcMapper.selectReportDcList(reportDc);
        //收油
        ArrayList<DataObj.TruckData> truckDataList1 = new ArrayList<>();

        ArrayList<DataObj.TruckData> truckDataList2 = new ArrayList<>();
//发油
        ArrayList<DataObj.TruckData> truckDataList3 = new ArrayList<>();

        ArrayList<DataObj.TruckData> truckDataList4 = new ArrayList<>();


        for (int i = 7; i >= 0; i--) {
            DataObj.TruckData truckData1 = new DataObj.TruckData();
            DataObj.TruckData truckData2 = new DataObj.TruckData();
            DataObj.TruckData truckData3 = new DataObj.TruckData();
            DataObj.TruckData truckData4 = new DataObj.TruckData();
            LocalDate localDate = LocalDate.parse(maxDc, formatterScreen);
            LocalDate date = localDate.minusDays(i);
            String dateString = date.format(formatterScreen);
            //收油重量
            BigDecimal totalWeight = chartDatesDc.stream()
                    .filter(dc -> dateString.equals(dc.getName()))
                    .map(ReportDc::getCollectWeight)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            truckData1.setCount(ObjectUtil.isNotEmpty(totalWeight)?totalWeight.toString():"");
            truckData1.setTime(dateString);
            truckDataList1.add(truckData1);
            BigDecimal totalCount = chartDatesDc.stream()
                    .filter(dc -> dateString.equals(dc.getName()))
                    .map(dc -> new BigDecimal(dc.getCollectCount()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            truckData2.setCount(ObjectUtil.isNotEmpty(totalCount)?totalCount.toString():"");
            truckData2.setTime(dateString);
            truckDataList2.add(truckData2);

            ObjectMapper objectMapper = new ObjectMapper();
            BigDecimal totalFayouWeight = chartDatesDc.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .flatMap(sc -> {
                        try {
                            String extra4 = sc.getExtra4();
                            if (extra4 == null || extra4.isEmpty()) {
                                return Stream.empty(); // 如果 extra4 为 null 或空字符串，返回空流
                            }
                            List<DepotJsonDto> extra4Items = objectMapper.readValue(
                                    extra4,
                                    new TypeReference<List<DepotJsonDto>>() {}
                            );
                            return extra4Items != null ? extra4Items.stream() : Stream.empty(); // 防止 extra4Items 为 null
                        } catch (Exception e) {
                            e.printStackTrace();
                            return Stream.empty(); // 如果解析失败，返回空流
                        }
                    })
                    .map(DepotJsonDto::getWeight)
                    .filter(Objects::nonNull) // 过滤掉 null 的 weight
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            truckData3.setCount(ObjectUtil.isNotEmpty(totalFayouWeight)?totalFayouWeight.toString():"");
            truckData3.setTime(dateString);
            truckDataList3.add(truckData3);
            BigDecimal totalFayouCount = chartDatesDc.stream().filter(dc -> dateString.equals(dc.getName()))
                    .flatMap(dc -> {
                        try {
                            // 将 extra4 转为 List<Extra4Item>
                            List<DepotJsonDto> extra4Items = objectMapper.readValue(
                                    dc.getExtra4(),
                                    new TypeReference<List<DepotJsonDto>>() {}
                            );
                            return extra4Items.stream(); // 返回 Extra4Item 流
                        } catch (Exception e) {
                            e.printStackTrace();
                            return Stream.empty(); // 如果解析失败，返回空流
                        }
                    })
                    .map(item -> {Integer count = item.getCount();
                        return count != null ? BigDecimal.valueOf(count) : BigDecimal.ZERO;}) // 将 int 转为 BigDecimal
                    .reduce(BigDecimal.ZERO, BigDecimal::add);        // 累加求和
            truckData4.setCount(ObjectUtil.isNotEmpty(totalFayouCount)?totalFayouCount.toString():"");
            truckData4.setTime(dateString);
            truckDataList4.add(truckData4);
        }
        DataObj.ChartData chartDataXxizang = new DataObj.ChartData();
        //收油重量
        chartDataXxizang.setGatherOilTruckTon(truckDataList1);
        //收油车数
        chartDataXxizang.setGatherOilTruckCount(truckDataList2);
        chartDataXxizang.setDistributeOilTruckTon(truckDataList3);
        chartDataXxizang.setDistributeOilTruckCount(truckDataList4);
        xizangDistributionCenter.setChartData(chartDataXxizang);
        if (CollectionUtil.isNotEmpty(reportDcs)){
            reportDcs=Collections.singletonList(reportDcs.get(0));
        }

        xizangDistributionCenter.setTableData(reportDcs);
        OilTank oilTank = new OilTank();
        oilTank.setDeptId(114L);
        List<OilTank> oilTanks = oilTankMapper.selectOilTankList(oilTank);

        xizangDistributionCenter.setOilTanks(oilTanks);


        dataObj.setXizangDistributionCenter(xizangDistributionCenter);



        ReportOilDepot reportOilDepot = new ReportOilDepot();
        reportOilDepot.setName(formattedDateYesterday);
        List<ReportOilDepot> reportOilDepots = depotMapper.selectReportOilDepotList(reportOilDepot);
        reportOilDepots=CollectionUtil.isNotEmpty(reportOilDepots)?Collections.singletonList(reportOilDepots.get(0)):new ArrayList<>();
        String maxDepot = depotMapper.maxName();
        DataObj.AirportOilDepotAndStation airportOilDepotAndStation = new DataObj.AirportOilDepotAndStation();
        if (CollectionUtil.isNotEmpty(reportOilDepots)){
            ReportOilDepot reportOilDepot1 = reportOilDepots.get(0);
            String extra2 = reportOilDepot1.getExtra2();
            List<Long> uids = gson.fromJson(extra2, userType);
            List<SysUser> correspondingReports = sysUsers.stream()
                    .filter(u -> uids.contains(u.getUserId())) // Assumes `ReportUserId` is now a collection of user IDs
                    .collect(Collectors.toList());

            String workNames = correspondingReports.stream()
                    .map(SysUser::getNickName)
                    .collect(Collectors.joining(", "));
            reportOilDepot1.setWorkName(workNames);
        }
        airportOilDepotAndStation.setTableDataYouku(reportOilDepots);
        OilTank oilTankYouku = new OilTank();
        //油库
        oilTankYouku.setDeptId(111L);

        List<OilTank> oilTanksYouku = oilTankMapper.selectOilTankList(oilTankYouku);
        airportOilDepotAndStation.setOilTanksYouku(oilTanksYouku);

        ReportGasStation reportGasStation = new ReportGasStation();
        reportGasStation.setName(formattedDateYesterday);
        List<ReportGasStation> reportGasStations = stationMapper.selectReportGasStationList(reportGasStation);
      String maxStation=  stationMapper.selectMaxName();
        BigDecimal averageFuelQuantityStation =BigDecimal.ZERO;
        BigDecimal totalFuelQuantityStation = BigDecimal.ZERO;
        Long countStation = 0l;
        for (int i = 0; i < 7; i++) {
            LocalDate localDate = LocalDate.parse(maxStation, formatterScreen);
            LocalDate date = localDate.minusDays(i);
            String dateString = date.format(formatterScreen);

            totalFuelQuantityStation = (reportGasStations.stream()
                    .filter(sc -> dateString.equals(sc.getName()) && sc.getFuelQuantity() != null) // 过滤出有值的条目
                    .map(ReportGasStation::getFuelQuantity)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)).add(totalFuelQuantityStation); // 求和

            countStation =countStation+ (reportGasStations.stream()
                    .filter(sc -> dateString.equals(sc.getName()) && sc.getFuelQuantity() != null) // 统计有值的条目数
                    .count());
        }
        averageFuelQuantityStation = countStation > 0
                ? totalFuelQuantityStation.divide(BigDecimal.valueOf(countStation), RoundingMode.HALF_UP) // 计算平均值
                : BigDecimal.ZERO; // 如果没有数据，平均值为0

        BigDecimal totalWeightMinusMinCap = oilTanksYouku.stream()
                .filter(o -> o.getTypeId() != 3 && o.getTypeId() != 4) // 过滤 typeId 不是 3 和 4 的对象
                .map(o -> o.getWeight().subtract(o.getMinCap())) // 计算 weight - minCap
                .reduce(BigDecimal.ZERO, BigDecimal::add); // 累加所有结果

        reportGasStations=CollectionUtil.isNotEmpty(reportGasStations)?Collections.singletonList(reportGasStations.get(0)):new ArrayList<>();
        if (CollectionUtil.isNotEmpty(reportGasStations)){
            ReportGasStation reportGasStation1 = reportGasStations.get(0);
            String carId = reportGasStation1.getCarId();

            if (StringUtils.isNotEmpty(carId)){
                Type listType = new TypeToken<List<Long>>() {}.getType();

                // 将 JSON 字符串转换为 List<Long>
                List<Long> longList = gson.fromJson(carId, listType);
                String licensePlates = cars.stream()
                        .filter(car -> longList.contains(car.getId())) // 筛选出符合条件的车
                        .map(ReportCarInfo::getLicensePlate) // 提取车牌号
                        .collect(Collectors.joining(",")); // 用逗号拼接
                reportGasStation1.setCarInfo(licensePlates);

                String extra2 = reportGasStation1.getExtra2();
                List<Long> uids = gson.fromJson(extra2, userType);
                List<SysUser> correspondingReports = sysUsers.stream()
                        .filter(u -> uids.contains(u.getUserId())) // Assumes `ReportUserId` is now a collection of user IDs
                        .collect(Collectors.toList());

                String workNames = correspondingReports.stream()
                        .map(SysUser::getNickName)
                        .collect(Collectors.joining(", "));
                reportGasStation1.setWorkName(workNames);



            }


            reportGasStation1.setAverageFuelQuantity(averageFuelQuantityStation);

            BigDecimal totalWeightMinusMinCapDc = oilTanks.stream()
                    .filter(o -> o.getTypeId() != 3 && o.getTypeId() != 4) // 过滤 typeId 不是 3 和 4 的对象
                    .map(o -> o.getWeight().subtract(o.getMinCap())) // 计算 weight - minCap
                    .reduce(BigDecimal.ZERO, BigDecimal::add); // 累加所有结果

            List<ReportDc> tableData = xizangDistributionCenter.getTableData();
            if (CollectionUtil.isNotEmpty(tableData)){
                ReportDc reportDc1 = tableData.get(0);
                reportDc1.setAverageFuelQuantity(averageFuelQuantityStation);
                if (ObjectUtil.isNotEmpty(averageFuelQuantityStation) &&
                        ObjectUtil.isNotEmpty(totalWeightMinusMinCapDc) &&
                        averageFuelQuantityStation.compareTo(BigDecimal.ZERO) > 0 &&
                        totalWeightMinusMinCapDc.compareTo(BigDecimal.ZERO) > 0) {

                    BigDecimal days = totalWeightMinusMinCapDc.divide(averageFuelQuantityStation, 2, RoundingMode.HALF_UP); // 指定保留两位小数，四舍五入
                    reportDc1.setDays(days);
                } else {
                    reportDc1.setDays(BigDecimal.ZERO); // 如果任一条件不满足，days 设置为 0
                }

                String extra2 = reportDc1.getExtra2();
                List<Long> uids = gson.fromJson(extra2, userType);
                List<SysUser> correspondingReports = sysUsers.stream()
                        .filter(u -> uids.contains(u.getUserId())) // Assumes `ReportUserId` is now a collection of user IDs
                        .collect(Collectors.toList());

                String workNames = correspondingReports.stream()
                        .map(SysUser::getNickName)
                        .collect(Collectors.joining(", "));
                reportDc1.setWorkName(workNames);
            }

            if (ObjectUtil.isNotEmpty(averageFuelQuantityStation) &&
                    ObjectUtil.isNotEmpty(totalWeightMinusMinCap) &&
                    averageFuelQuantityStation.compareTo(BigDecimal.ZERO) > 0 &&
                    totalWeightMinusMinCap.compareTo(BigDecimal.ZERO) > 0) {

                BigDecimal days = totalWeightMinusMinCap.divide(averageFuelQuantityStation, 2, RoundingMode.HALF_UP); // 指定保留两位小数，四舍五入
                reportGasStation1.setDays(days);
            } else {
                reportGasStation1.setDays(BigDecimal.ZERO); // 如果任一条件不满足，days 设置为 0
            }


        }
        airportOilDepotAndStation.setTableDataLasa(reportGasStations);


        reportOilDepot.setName(null);
        reportOilDepot.setStart(formattedDate7day);
        reportOilDepot.setEnd(formattedDate);
        List<ReportOilDepot> chartDatesDepot = depotMapper.selectReportOilDepotList(reportOilDepot);


        reportGasStation.setName(null);
        reportGasStation.setStart(formattedDate7day);
        reportGasStation.setEnd(formattedDate);
        List<ReportGasStation> chartDatesStation = stationMapper.selectReportGasStationList(reportGasStation);

        //收油
        ArrayList<DataObj.TruckData> depottruckDataList1 = new ArrayList<>();

        ArrayList<DataObj.TruckData> depottruckDataList2 = new ArrayList<>();
//发油
        ArrayList<DataObj.TruckData> depottruckDataList3 = new ArrayList<>();

        ArrayList<DataObj.TruckData> depottruckDataList4 = new ArrayList<>();
//加油
        ArrayList<DataObj.TruckData> depottruckDataList5 = new ArrayList<>();

        ArrayList<DataObj.TruckData> depottruckDataList6 = new ArrayList<>();



        for (int i = 7; i >= 0; i--) {
            DataObj.TruckData truckData1 = new DataObj.TruckData();
            DataObj.TruckData truckData2 = new DataObj.TruckData();
            DataObj.TruckData truckData3 = new DataObj.TruckData();
            DataObj.TruckData truckData4 = new DataObj.TruckData();
            DataObj.TruckData truckData5 = new DataObj.TruckData();
            DataObj.TruckData truckData6 = new DataObj.TruckData();

            LocalDate localDate = LocalDate.parse(maxDepot, formatterScreen);
            LocalDate date = localDate.minusDays(i);
            String dateString = date.format(formatterScreen);

            BigDecimal totalJiayouCount = chartDatesStation.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .map(dc -> new BigDecimal(dc.getOilCount()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            truckData5.setTime(dateString);
            truckData5.setCount(ObjectUtil.isNotEmpty(totalJiayouCount)?totalJiayouCount.toString():"");
            depottruckDataList5.add(truckData5);
            BigDecimal totalJiayouWeight = chartDatesStation.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .map(dc -> dc.getFuelQuantity())
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            truckData6.setTime(dateString);
            truckData6.setCount(ObjectUtil.isNotEmpty(totalJiayouWeight)?totalJiayouWeight.toString():"");
            depottruckDataList6.add(truckData6);

            //收油重量
            BigDecimal totalWeight = chartDatesDepot.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .map(ReportOilDepot::getCollectWeight)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            truckData1.setCount(ObjectUtil.isNotEmpty(totalWeight)?totalWeight.toString():"");
            truckData1.setTime(dateString);
            depottruckDataList1.add(truckData1);
            BigDecimal totalCount = chartDatesDepot.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .map(dc -> new BigDecimal(dc.getCollectCount()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            truckData2.setCount(ObjectUtil.isNotEmpty(totalCount)?totalCount.toString():"");
            truckData2.setTime(dateString);
            depottruckDataList2.add(truckData2);

            ObjectMapper objectMapper = new ObjectMapper();
            BigDecimal totalFayouWeight = chartDatesDepot.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .flatMap(sc -> {
                        try {
                            String extra4 = sc.getExtra4();
                            if (extra4 == null || extra4.isEmpty()) {
                                return Stream.empty(); // 如果 extra4 为 null 或空字符串，返回空流
                            }
                            List<DepotJsonDto> extra4Items = objectMapper.readValue(
                                    extra4,
                                    new TypeReference<List<DepotJsonDto>>() {}
                            );
                            return extra4Items != null ? extra4Items.stream() : Stream.empty(); // 防止 extra4Items 为 null
                        } catch (Exception e) {
                            e.printStackTrace();
                            return Stream.empty(); // 如果解析失败，返回空流
                        }
                    })
                    .map(DepotJsonDto::getWeight)
                    .filter(Objects::nonNull) // 过滤掉 null 的 weight
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            truckData3.setCount(ObjectUtil.isNotEmpty(totalFayouWeight)?totalFayouWeight.toString():"");
            truckData3.setTime(dateString);
            depottruckDataList3.add(truckData3);
            BigDecimal totalFayouCount = chartDatesDepot.stream().filter(sc -> dateString.equals(sc.getName()))
                    .flatMap(dc -> {
                        try {
                            // 将 extra4 转为 List<Extra4Item>
                            List<DepotJsonDto> extra4Items = objectMapper.readValue(
                                    dc.getExtra4(),
                                    new TypeReference<List<DepotJsonDto>>() {}
                            );
                            return extra4Items.stream(); // 返回 Extra4Item 流
                        } catch (Exception e) {
                            e.printStackTrace();
                            return Stream.empty(); // 如果解析失败，返回空流
                        }
                    })
                    .map(item -> {Integer count = item.getCount();
                        return count != null ? BigDecimal.valueOf(count) : BigDecimal.ZERO;}) // 将 int 转为 BigDecimal
                    .reduce(BigDecimal.ZERO, BigDecimal::add);        // 累加求和
            truckData4.setCount(ObjectUtil.isNotEmpty(totalFayouCount)?totalFayouCount.toString():"");
            truckData4.setTime(dateString);
            depottruckDataList4.add(truckData4);
        }
        DataObj.ChartData chartDataDepot = new DataObj.ChartData();
        //收油重量
        chartDataDepot.setGatherOilTruckTon(depottruckDataList6);
        //收油车数
        chartDataDepot.setGatherOilTruckCount(depottruckDataList5);
        chartDataDepot.setDistributeOilTruckTon(depottruckDataList3);
        chartDataDepot.setDistributeOilTruckCount(depottruckDataList4);
//        chartDataDepot.setJiayouOilTruckCount(depottruckDataList5);
//        chartDataDepot.setJiayouOilTruckTon(depottruckDataList6);
        airportOilDepotAndStation.setChartData(chartDataDepot);

        //拉萨
        oilTankYouku.setDeptId(110L);
        List<OilTank> oilTanksLasa = oilTankMapper.selectOilTankList(oilTankYouku);
        airportOilDepotAndStation.setOilTanksLasa(oilTanksLasa);

        dataObj.setAirportOilDepotAndStation(airportOilDepotAndStation);


        ReportSc reportSc = new ReportSc();
        reportSc.setDeptId(107L);
        String maxLinzhi = reportScMapper.selectMaxName(reportSc);
        reportSc.setName(formattedDateYesterday);
        oilTank.setDeptId(107L);
        List<OilTank> oilTankLinzhi = oilTankMapper.selectOilTankList(oilTank);
        List<ReportSc> reportScs = reportScMapper.selectReportScList(reportSc);
        reportScs=CollectionUtil.isNotEmpty(reportScs)?Collections.singletonList(reportScs.get(0)):new ArrayList<>();
        DataObj.LinzhiSupplyStation linzhiSupplyStation = new DataObj.LinzhiSupplyStation();
        linzhiSupplyStation.setOilTanks(oilTankLinzhi);
       // linzhiSupplyStation.setTableData(reportScs);



        reportSc.setName(null);
        reportSc.setStart(formattedDate7day);
        reportSc.setEnd(formattedDate);
        List<ReportSc> chartDatesSc = reportScMapper.selectReportScList(reportSc);
        //收油
        ArrayList<DataObj.TruckData> linzhitruckDataList1 = new ArrayList<>();

        ArrayList<DataObj.TruckData> linzhitruckDataList2 = new ArrayList<>();
//发油
        ArrayList<DataObj.TruckData> linzhitruckDataList3 = new ArrayList<>();

        ArrayList<DataObj.TruckData> linzhitruckDataList4 = new ArrayList<>();
//加油
        ArrayList<DataObj.TruckData> linzhitruckDataList5 = new ArrayList<>();

        ArrayList<DataObj.TruckData> linzhitruckDataList6 = new ArrayList<>();

        BigDecimal averageFuelQuantityLinzhi =BigDecimal.ZERO;
        BigDecimal totalFuelQuantityLinzhi = BigDecimal.ZERO;
        Long countLinzhi = 0l;

        for (int i = 7; i >= 0; i--) {
            DataObj.TruckData truckData1 = new DataObj.TruckData();
            DataObj.TruckData truckData2 = new DataObj.TruckData();
            DataObj.TruckData truckData3 = new DataObj.TruckData();
            DataObj.TruckData truckData4 = new DataObj.TruckData();
            DataObj.TruckData truckData5 = new DataObj.TruckData();
            DataObj.TruckData truckData6 = new DataObj.TruckData();
            LocalDate localDate = LocalDate.parse(maxLinzhi, formatterScreen);
            LocalDate date = localDate.minusDays(i);
            String dateString = date.format(formatterScreen);
            //收油重量
            BigDecimal totalWeight = chartDatesSc.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .map(ReportSc::getCollectWeight)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            totalFuelQuantityLinzhi = (chartDatesSc.stream()
                    .filter(sc -> dateString.equals(sc.getName()) && sc.getFuelQuantity() != null) // 过滤出有值的条目
                    .map(ReportSc::getFuelQuantity)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)).add(totalFuelQuantityLinzhi); // 求和

            countLinzhi =countLinzhi+ (chartDatesSc.stream()
                    .filter(sc -> dateString.equals(sc.getName()) && sc.getFuelQuantity() != null) // 统计有值的条目数
                    .count());
            BigDecimal totalJiayouCount = chartDatesSc.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .map(dc -> new BigDecimal(dc.getOilCount()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            truckData5.setTime(dateString);
            truckData5.setCount(ObjectUtil.isNotEmpty(totalJiayouCount)?totalJiayouCount.toString():"");
            linzhitruckDataList5.add(truckData5);
            BigDecimal totalJiayouWeight = chartDatesSc.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .map(dc -> dc.getFuelQuantity())
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            truckData6.setTime(dateString);
            truckData6.setCount(ObjectUtil.isNotEmpty(totalJiayouWeight)?totalJiayouWeight.toString():"");
            linzhitruckDataList6.add(truckData6);
            truckData1.setCount(ObjectUtil.isNotEmpty(totalWeight)?totalWeight.toString():"");
            truckData1.setTime(dateString);
            linzhitruckDataList1.add(truckData1);
            BigDecimal totalCount = chartDatesSc.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .map(dc -> new BigDecimal(dc.getCollectCount()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            truckData2.setCount(ObjectUtil.isNotEmpty(totalCount)?totalCount.toString():"");
            truckData2.setTime(dateString);
            linzhitruckDataList2.add(truckData2);

            ObjectMapper objectMapper = new ObjectMapper();
            BigDecimal totalFayouWeight = chartDatesSc.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .flatMap(sc -> {
                        try {
                            String extra4 = sc.getExtra4();
                            if (extra4 == null || extra4.isEmpty()) {
                                return Stream.empty(); // 如果 extra4 为 null 或空字符串，返回空流
                            }
                            List<DepotJsonDto> extra4Items = objectMapper.readValue(
                                    extra4,
                                    new TypeReference<List<DepotJsonDto>>() {}
                            );
                            return extra4Items != null ? extra4Items.stream() : Stream.empty(); // 防止 extra4Items 为 null
                        } catch (Exception e) {
                            e.printStackTrace();
                            return Stream.empty(); // 如果解析失败，返回空流
                        }
                    })
                    .map(DepotJsonDto::getWeight)
                    .filter(Objects::nonNull) // 过滤掉 null 的 weight
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            truckData3.setCount(ObjectUtil.isNotEmpty(totalFayouWeight)?totalFayouWeight.toString():"");
            truckData3.setTime(dateString);
            linzhitruckDataList3.add(truckData3);
            BigDecimal totalFayouCount = chartDatesSc.stream().filter(sc -> dateString.equals(sc.getName()))
                    .flatMap(dc -> {
                        try {
                            // 将 extra4 转为 List<Extra4Item>
                            List<DepotJsonDto> extra4Items = objectMapper.readValue(
                                    dc.getExtra4(),
                                    new TypeReference<List<DepotJsonDto>>() {}
                            );
                            return extra4Items.stream(); // 返回 Extra4Item 流
                        } catch (Exception e) {
                            e.printStackTrace();
                            return Stream.empty(); // 如果解析失败，返回空流
                        }
                    })
                    .map(item -> {Integer count = item.getCount();
                        return count != null ? BigDecimal.valueOf(count) : BigDecimal.ZERO;}) // 将 int 转为 BigDecimal
                    .reduce(BigDecimal.ZERO, BigDecimal::add);        // 累加求和
            truckData4.setCount(ObjectUtil.isNotEmpty(totalFayouCount)?totalFayouCount.toString():"");
            truckData4.setTime(dateString);
            linzhitruckDataList4.add(truckData4);
        }

        averageFuelQuantityLinzhi = countLinzhi > 0
                ? totalFuelQuantityLinzhi.divide(BigDecimal.valueOf(countLinzhi), RoundingMode.HALF_UP) // 计算平均值
                : BigDecimal.ZERO; // 如果没有数据，平均值为0

        BigDecimal totalWeightMinusMinCapLinzhi = oilTankLinzhi.stream()
                .filter(o -> o.getTypeId() != 3 && o.getTypeId() != 4) // 过滤 typeId 不是 3 和 4 的对象
                .map(o -> o.getWeight().subtract(o.getMinCap())) // 计算 weight - minCap
                .reduce(BigDecimal.ZERO, BigDecimal::add); // 累加所有结果

        if (CollectionUtil.isNotEmpty(reportScs)){
            ReportSc reportSc1 = reportScs.get(0);
            reportSc1.setAverageFuelQuantity(averageFuelQuantityLinzhi);
            String carId = reportSc1.getCarId();
            if (StringUtils.isNotEmpty(carId)){
                Type listType = new TypeToken<List<Long>>() {}.getType();

                // 将 JSON 字符串转换为 List<Long>
                List<Long> longList = gson.fromJson(carId, listType);
                String licensePlates = cars.stream()
                        .filter(car -> longList.contains(car.getId())) // 筛选出符合条件的车
                        .map(ReportCarInfo::getLicensePlate) // 提取车牌号
                        .collect(Collectors.joining(",")); // 用逗号拼接
                reportSc1.setCarInfo(licensePlates);

                String extra2 = reportSc1.getExtra2();
                List<Long> uids = gson.fromJson(extra2, userType);
                List<SysUser> correspondingReports = sysUsers.stream()
                        .filter(u -> uids.contains(u.getUserId())) // Assumes `ReportUserId` is now a collection of user IDs
                        .collect(Collectors.toList());

                String workNames = correspondingReports.stream()
                        .map(SysUser::getNickName)
                        .collect(Collectors.joining(", "));
                reportSc1.setWorkName(workNames);
            }


            if (ObjectUtil.isNotEmpty(averageFuelQuantityLinzhi) &&
                    ObjectUtil.isNotEmpty(totalWeightMinusMinCapLinzhi) &&
                    averageFuelQuantityLinzhi.compareTo(BigDecimal.ZERO) > 0 &&
                    totalWeightMinusMinCapLinzhi.compareTo(BigDecimal.ZERO) > 0) {

                BigDecimal days = totalWeightMinusMinCapLinzhi.divide(averageFuelQuantityLinzhi, 2, RoundingMode.HALF_UP); // 指定保留两位小数，四舍五入
                reportSc1.setDays(days);
            } else {
                reportSc1.setDays(BigDecimal.ZERO); // 如果任一条件不满足，days 设置为 0
            }
        }
        linzhiSupplyStation.setTableData(reportScs);
        DataObj.ChartData chartDataLinzhi = new DataObj.ChartData();
        //收油重量
        chartDataLinzhi.setGatherOilTruckTon(linzhitruckDataList5);
        //收油车数
        chartDataLinzhi.setGatherOilTruckCount(linzhitruckDataList6);
        chartDataLinzhi.setDistributeOilTruckTon(linzhitruckDataList3);
        chartDataLinzhi.setDistributeOilTruckCount(linzhitruckDataList4);
//        chartDataLinzhi.setJiayouOilTruckCount(linzhitruckDataList5);
//        chartDataLinzhi.setJiayouOilTruckTon(linzhitruckDataList6);
        linzhiSupplyStation.setChartData(chartDataLinzhi);
        dataObj.setLinzhiSupplyStation(linzhiSupplyStation);


        reportSc.setDeptId(108L);
        String maxAli = reportScMapper.selectMaxName(reportSc);
        reportSc.setName(formattedDateYesterday);
        oilTank.setDeptId(108L);
        List<OilTank> oilTankAli = oilTankMapper.selectOilTankList(oilTank);
        List<ReportSc> reportScsAli = reportScMapper.selectReportScList(reportSc);
        reportScsAli=CollectionUtil.isNotEmpty(reportScsAli)?Collections.singletonList(reportScsAli.get(0)):new ArrayList<>();
        DataObj.AliSupplyStation aliSupplyStation = new DataObj.AliSupplyStation();
        aliSupplyStation.setOilTanks(oilTankAli);



        reportSc.setName(null);
        reportSc.setStart(formattedDate7day);
        reportSc.setEnd(formattedDate);
        List<ReportSc> chartDatesScAli = reportScMapper.selectReportScList(reportSc);
        //收油
        ArrayList<DataObj.TruckData> alitruckDataList1 = new ArrayList<>();

        ArrayList<DataObj.TruckData> alitruckDataList2 = new ArrayList<>();
//发油
        ArrayList<DataObj.TruckData> alitruckDataList3 = new ArrayList<>();

        ArrayList<DataObj.TruckData> alitruckDataList4 = new ArrayList<>();

        //加油
        ArrayList<DataObj.TruckData> alitruckDataList5 = new ArrayList<>();

        ArrayList<DataObj.TruckData> alitruckDataList6 = new ArrayList<>();

        BigDecimal averageFuelQuantityAli =BigDecimal.ZERO;
        BigDecimal totalFuelQuantityAli = BigDecimal.ZERO;
        Long countAli = 0l;

        for (int i = 7; i >= 0; i--) {
            DataObj.TruckData truckData1 = new DataObj.TruckData();
            DataObj.TruckData truckData2 = new DataObj.TruckData();
            DataObj.TruckData truckData3 = new DataObj.TruckData();
            DataObj.TruckData truckData4 = new DataObj.TruckData();
            DataObj.TruckData truckData5 = new DataObj.TruckData();
            DataObj.TruckData truckData6 = new DataObj.TruckData();
            LocalDate localDate = LocalDate.parse(maxAli, formatterScreen);
            LocalDate date = localDate.minusDays(i);
            String dateString = date.format(formatterScreen);


            totalFuelQuantityAli = (chartDatesScAli.stream()
                    .filter(sc -> dateString.equals(sc.getName()) && sc.getFuelQuantity() != null) // 过滤出有值的条目
                    .map(ReportSc::getFuelQuantity)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)).add(totalFuelQuantityAli); // 求和

            countAli =countAli+ (chartDatesScAli.stream()
                    .filter(sc -> dateString.equals(sc.getName()) && sc.getFuelQuantity() != null) // 统计有值的条目数
                    .count());


            //收油重量
            BigDecimal totalWeight = chartDatesScAli.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .map(ReportSc::getCollectWeight)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            truckData1.setCount(ObjectUtil.isNotEmpty(totalWeight)?totalWeight.toString():"");
            truckData1.setTime(dateString);
            alitruckDataList1.add(truckData1);
            BigDecimal totalCount = chartDatesScAli.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .map(dc -> new BigDecimal(dc.getCollectCount()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            truckData2.setCount(ObjectUtil.isNotEmpty(totalCount)?totalCount.toString():"");
            truckData2.setTime(dateString);
            alitruckDataList2.add(truckData2);

            BigDecimal totalJiayouCount = chartDatesSc.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .map(dc -> new BigDecimal(dc.getOilCount()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            truckData5.setTime(dateString);
            truckData5.setCount(ObjectUtil.isNotEmpty(totalJiayouCount)?totalJiayouCount.toString():"");
            alitruckDataList5.add(truckData5);
            BigDecimal totalJiayouWeight = chartDatesSc.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .map(dc -> dc.getFuelQuantity())
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            truckData6.setTime(dateString);
            truckData6.setCount(ObjectUtil.isNotEmpty(totalJiayouWeight)?totalJiayouWeight.toString():"");
            alitruckDataList6.add(truckData6);

            ObjectMapper objectMapper = new ObjectMapper();
            BigDecimal totalFayouWeight = chartDatesScAli.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .flatMap(sc -> {
                        try {
                            String extra4 = sc.getExtra4();
                            if (extra4 == null || extra4.isEmpty()) {
                                return Stream.empty(); // 如果 extra4 为 null 或空字符串，返回空流
                            }
                            List<DepotJsonDto> extra4Items = objectMapper.readValue(
                                    extra4,
                                    new TypeReference<List<DepotJsonDto>>() {}
                            );
                            return extra4Items != null ? extra4Items.stream() : Stream.empty(); // 防止 extra4Items 为 null
                        } catch (Exception e) {
                            e.printStackTrace();
                            return Stream.empty(); // 如果解析失败，返回空流
                        }
                    })
                    .map(DepotJsonDto::getWeight)
                    .filter(Objects::nonNull) // 过滤掉 null 的 weight
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            truckData3.setCount(ObjectUtil.isNotEmpty(totalFayouWeight)?totalFayouWeight.toString():"");
            truckData3.setTime(dateString);
            alitruckDataList3.add(truckData3);
            BigDecimal totalFayouCount = chartDatesScAli.stream().filter(sc -> dateString.equals(sc.getName()))
                    .flatMap(dc -> {
                        try {
                            // 将 extra4 转为 List<Extra4Item>
                            List<DepotJsonDto> extra4Items = objectMapper.readValue(
                                    dc.getExtra4(),
                                    new TypeReference<List<DepotJsonDto>>() {}
                            );
                            return extra4Items.stream(); // 返回 Extra4Item 流
                        } catch (Exception e) {
                            e.printStackTrace();
                            return Stream.empty(); // 如果解析失败，返回空流
                        }
                    })
                    .map(item -> {Integer count = item.getCount();
                        return count != null ? BigDecimal.valueOf(count) : BigDecimal.ZERO;}) // 将 int 转为 BigDecimal
                    .reduce(BigDecimal.ZERO, BigDecimal::add);        // 累加求和
            truckData4.setCount(ObjectUtil.isNotEmpty(totalFayouCount)?totalFayouCount.toString():"");
            truckData4.setTime(dateString);
            alitruckDataList4.add(truckData4);
        }

        averageFuelQuantityAli = countAli > 0
                ? totalFuelQuantityAli.divide(BigDecimal.valueOf(countAli), RoundingMode.HALF_UP) // 计算平均值
                : BigDecimal.ZERO; // 如果没有数据，平均值为0

        BigDecimal totalWeightMinusMinCapAli = oilTankAli.stream()
                .filter(o -> o.getTypeId() != 3 && o.getTypeId() != 4) // 过滤 typeId 不是 3 和 4 的对象
                .map(o -> o.getWeight().subtract(o.getMinCap())) // 计算 weight - minCap
                .reduce(BigDecimal.ZERO, BigDecimal::add); // 累加所有结果

        if (CollectionUtil.isNotEmpty(reportScsAli)){
            ReportSc reportSc1 = reportScsAli.get(0);
            reportSc1.setAverageFuelQuantity(averageFuelQuantityAli);

            String carId = reportSc1.getCarId();
            if (StringUtils.isNotEmpty(carId)){
                Type listType = new TypeToken<List<Long>>() {}.getType();

                // 将 JSON 字符串转换为 List<Long>
                List<Long> longList = gson.fromJson(carId, listType);
                String licensePlates = cars.stream()
                        .filter(car -> longList.contains(car.getId())) // 筛选出符合条件的车
                        .map(ReportCarInfo::getLicensePlate) // 提取车牌号
                        .collect(Collectors.joining(",")); // 用逗号拼接
                reportSc1.setCarInfo(licensePlates);

                String extra2 = reportSc1.getExtra2();
                List<Long> uids = gson.fromJson(extra2, userType);
                List<SysUser> correspondingReports = sysUsers.stream()
                        .filter(u -> uids.contains(u.getUserId())) // Assumes `ReportUserId` is now a collection of user IDs
                        .collect(Collectors.toList());

                String workNames = correspondingReports.stream()
                        .map(SysUser::getNickName)
                        .collect(Collectors.joining(", "));
                reportSc1.setWorkName(workNames);

            }
            if (ObjectUtil.isNotEmpty(averageFuelQuantityAli) &&
                    ObjectUtil.isNotEmpty(totalWeightMinusMinCapAli) &&
                    averageFuelQuantityAli.compareTo(BigDecimal.ZERO) > 0 &&
                    totalWeightMinusMinCapAli.compareTo(BigDecimal.ZERO) > 0) {

                BigDecimal days = totalWeightMinusMinCapAli.divide(averageFuelQuantityAli, 2, RoundingMode.HALF_UP); // 指定保留两位小数，四舍五入
                reportSc1.setDays(days);
            } else {
                reportSc1.setDays(BigDecimal.ZERO); // 如果任一条件不满足，days 设置为 0
            }
        }
        aliSupplyStation.setTableData(reportScsAli);
        DataObj.ChartData chartDataAli = new DataObj.ChartData();
        //收油重量
        chartDataAli.setGatherOilTruckTon(alitruckDataList6);
        //收油车数
        chartDataAli.setGatherOilTruckCount(alitruckDataList5);
        chartDataAli.setDistributeOilTruckTon(alitruckDataList3);
        chartDataAli.setDistributeOilTruckCount(alitruckDataList4);
//        chartDataAli.setJiayouOilTruckCount(alitruckDataList5);
//        chartDataAli.setJiayouOilTruckTon(alitruckDataList6);
        aliSupplyStation.setChartData(chartDataAli);
        dataObj.setAliSupplyStation(aliSupplyStation);



        reportSc.setDeptId(109L);
        String maxRikeze = reportScMapper.selectMaxName(reportSc);
        reportSc.setName(formattedDateYesterday);
        oilTank.setDeptId(109L);
        List<OilTank> oilTankRikeze = oilTankMapper.selectOilTankList(oilTank);
        List<ReportSc> reportScRikeze = reportScMapper.selectReportScList(reportSc);
        reportScRikeze=CollectionUtil.isNotEmpty(reportScRikeze)?Collections.singletonList(reportScRikeze.get(0)):new ArrayList<>();
        DataObj.RikezeSupplyStation rikezeSupplyStation = new DataObj.RikezeSupplyStation();
        rikezeSupplyStation.setOilTanks(oilTankRikeze);

        reportSc.setName(null);
        reportSc.setStart(formattedDate7day);
        reportSc.setEnd(formattedDate);
        List<ReportSc> chartDatesScRikeze = reportScMapper.selectReportScList(reportSc);
        //收油
        ArrayList<DataObj.TruckData> rikezetruckDataList1 = new ArrayList<>();

        ArrayList<DataObj.TruckData> rikezetruckDataList2 = new ArrayList<>();
//发油
        ArrayList<DataObj.TruckData> rikezetruckDataList3 = new ArrayList<>();

        ArrayList<DataObj.TruckData> rikezetruckDataList4 = new ArrayList<>();

        //加油
        ArrayList<DataObj.TruckData> rikezetruckDataList5 = new ArrayList<>();

        ArrayList<DataObj.TruckData> rikezetruckDataList6 = new ArrayList<>();
        BigDecimal averageFuelQuantityRikeze =BigDecimal.ZERO;
        BigDecimal totalFuelQuantityRikeze = BigDecimal.ZERO;
        Long countRikeze = 0l;

        for (int i = 7; i >= 0; i--) {
            DataObj.TruckData truckData1 = new DataObj.TruckData();
            DataObj.TruckData truckData2 = new DataObj.TruckData();
            DataObj.TruckData truckData3 = new DataObj.TruckData();
            DataObj.TruckData truckData4 = new DataObj.TruckData();
            DataObj.TruckData truckData5 = new DataObj.TruckData();
            DataObj.TruckData truckData6 = new DataObj.TruckData();
            LocalDate localDate = LocalDate.parse(maxRikeze, formatterScreen);
            LocalDate date = localDate.minusDays(i);
            String dateString = date.format(formatterScreen);

            totalFuelQuantityRikeze = (chartDatesScRikeze.stream()
                    .filter(sc -> dateString.equals(sc.getName()) && sc.getFuelQuantity() != null) // 过滤出有值的条目
                    .map(ReportSc::getFuelQuantity)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)).add(totalFuelQuantityRikeze); // 求和

            countRikeze =countRikeze+ (chartDatesScRikeze.stream()
                    .filter(sc -> dateString.equals(sc.getName()) && sc.getFuelQuantity() != null) // 统计有值的条目数
                    .count());

            //收油重量
            BigDecimal totalWeight = chartDatesScRikeze.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .map(ReportSc::getCollectWeight)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            truckData1.setCount(ObjectUtil.isNotEmpty(totalWeight)?totalWeight.toString():"");
            truckData1.setTime(dateString);
            rikezetruckDataList1.add(truckData1);
            BigDecimal totalCount = chartDatesScRikeze.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .map(dc -> new BigDecimal(dc.getCollectCount()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            truckData2.setCount(ObjectUtil.isNotEmpty(totalCount)?totalCount.toString():"");
            truckData2.setTime(dateString);
            rikezetruckDataList2.add(truckData2);

            BigDecimal totalJiayouCount = chartDatesSc.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .map(dc -> new BigDecimal(dc.getOilCount()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            truckData5.setTime(dateString);
            truckData5.setCount(ObjectUtil.isNotEmpty(totalJiayouCount)?totalJiayouCount.toString():"");
            rikezetruckDataList5.add(truckData5);
            BigDecimal totalJiayouWeight = chartDatesSc.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .map(dc -> dc.getFuelQuantity())
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            truckData6.setTime(dateString);
            truckData6.setCount(ObjectUtil.isNotEmpty(totalJiayouWeight)?totalJiayouWeight.toString():"");
            rikezetruckDataList6.add(truckData6);

            ObjectMapper objectMapper = new ObjectMapper();
            BigDecimal totalFayouWeight = chartDatesScRikeze.stream()
                    .filter(sc -> dateString.equals(sc.getName()))
                    .flatMap(sc -> {
                        try {
                            String extra4 = sc.getExtra4();
                            if (extra4 == null || extra4.isEmpty()) {
                                return Stream.empty(); // 如果 extra4 为 null 或空字符串，返回空流
                            }
                            List<DepotJsonDto> extra4Items = objectMapper.readValue(
                                    extra4,
                                    new TypeReference<List<DepotJsonDto>>() {}
                            );
                            return extra4Items != null ? extra4Items.stream() : Stream.empty(); // 防止 extra4Items 为 null
                        } catch (Exception e) {
                            e.printStackTrace();
                            return Stream.empty(); // 如果解析失败，返回空流
                        }
                    })
                    .map(DepotJsonDto::getWeight)
                    .filter(Objects::nonNull) // 过滤掉 null 的 weight
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            truckData3.setCount(ObjectUtil.isNotEmpty(totalFayouWeight)?totalFayouWeight.toString():"");
            truckData3.setTime(dateString);
            rikezetruckDataList3.add(truckData3);
            BigDecimal totalFayouCount = chartDatesScRikeze.stream().filter(sc -> dateString.equals(sc.getName()))
                    .flatMap(dc -> {
                        try {
                            // 将 extra4 转为 List<Extra4Item>
                            List<DepotJsonDto> extra4Items = objectMapper.readValue(
                                    dc.getExtra4(),
                                    new TypeReference<List<DepotJsonDto>>() {}
                            );
                            return extra4Items.stream(); // 返回 Extra4Item 流
                        } catch (Exception e) {
                            e.printStackTrace();
                            return Stream.empty(); // 如果解析失败，返回空流
                        }
                    })
                    .map(item -> {
                        Integer count = item.getCount();
                        return count != null ? BigDecimal.valueOf(count) : BigDecimal.ZERO;
                    }) // 将 int 转为 BigDecimal
                    .reduce(BigDecimal.ZERO, BigDecimal::add);        // 累加求和
            truckData4.setCount(ObjectUtil.isNotEmpty(totalFayouCount)?totalFayouCount.toString():"");
            truckData4.setTime(dateString);
            rikezetruckDataList4.add(truckData4);
        }
        averageFuelQuantityRikeze = countRikeze > 0
                ? totalFuelQuantityRikeze.divide(BigDecimal.valueOf(countRikeze), RoundingMode.HALF_UP) // 计算平均值
                : BigDecimal.ZERO; // 如果没有数据，平均值为0

        BigDecimal totalWeightMinusMinCapRikeze = oilTankRikeze.stream()
                .filter(o -> o.getTypeId() != 3 && o.getTypeId() != 4) // 过滤 typeId 不是 3 和 4 的对象
                .map(o -> o.getWeight().subtract(o.getMinCap())) // 计算 weight - minCap
                .reduce(BigDecimal.ZERO, BigDecimal::add); // 累加所有结果

        if (CollectionUtil.isNotEmpty(reportScRikeze)){
            ReportSc reportSc1 = reportScRikeze.get(0);
            reportSc1.setAverageFuelQuantity(averageFuelQuantityRikeze);
            String carId = reportSc1.getCarId();
            if (StringUtils.isNotEmpty(carId)){
                Type listType = new TypeToken<List<Long>>() {}.getType();

                // 将 JSON 字符串转换为 List<Long>
                List<Long> longList = gson.fromJson(carId, listType);
                String licensePlates = cars.stream()
                        .filter(car -> longList.contains(car.getId())) // 筛选出符合条件的车
                        .map(ReportCarInfo::getLicensePlate) // 提取车牌号
                        .collect(Collectors.joining(",")); // 用逗号拼接
                reportSc1.setCarInfo(licensePlates);

                String extra2 = reportSc1.getExtra2();
                List<Long> uids = gson.fromJson(extra2, userType);
                List<SysUser> correspondingReports = sysUsers.stream()
                        .filter(u -> uids.contains(u.getUserId())) // Assumes `ReportUserId` is now a collection of user IDs
                        .collect(Collectors.toList());

                String workNames = correspondingReports.stream()
                        .map(SysUser::getNickName)
                        .collect(Collectors.joining(", "));
                reportSc1.setWorkName(workNames);
            }
            if (ObjectUtil.isNotEmpty(averageFuelQuantityRikeze) &&
                    ObjectUtil.isNotEmpty(totalWeightMinusMinCapRikeze) &&
                    averageFuelQuantityRikeze.compareTo(BigDecimal.ZERO) > 0 &&
                    totalWeightMinusMinCapRikeze.compareTo(BigDecimal.ZERO) > 0) {

                BigDecimal days = totalWeightMinusMinCapRikeze.divide(averageFuelQuantityRikeze, 2, RoundingMode.HALF_UP); // 指定保留两位小数，四舍五入
                reportSc1.setDays(days);
            } else {
                reportSc1.setDays(BigDecimal.ZERO); // 如果任一条件不满足，days 设置为 0
            }
        }
        rikezeSupplyStation.setTableData(reportScRikeze);
        DataObj.ChartData chartDataRikeze = new DataObj.ChartData();
        //收油重量
        chartDataRikeze.setGatherOilTruckTon(rikezetruckDataList6);
        //收油车数
        chartDataRikeze.setGatherOilTruckCount(rikezetruckDataList5);
        chartDataRikeze.setDistributeOilTruckTon(rikezetruckDataList3);
        chartDataRikeze.setDistributeOilTruckCount(rikezetruckDataList4);
//        chartDataRikeze.setJiayouOilTruckCount(rikezetruckDataList5);
//        chartDataRikeze.setJiayouOilTruckTon(rikezetruckDataList6);
        rikezeSupplyStation.setChartData(chartDataRikeze);

        dataObj.setRikezeSupplyStation(rikezeSupplyStation);

        List<LatestExamScore> latestExamScores = userScoreMapper.getLatestExamScores();
        DataObj.ExamStatus examStatus = new DataObj.ExamStatus();
        examStatus.setTableData(latestExamScores);
        dataObj.setExamStatus(examStatus);

        List<TodayStudyLog> todayStudyLogs = userStudyLogMapper.getTodayStudyLogs();
        DataObj.PersonnelLearningStatus personnelLearningStatus = new DataObj.PersonnelLearningStatus();
        personnelLearningStatus.setTableData(todayStudyLogs);
        dataObj.setPersonnelLearningStatus(personnelLearningStatus);

        dataObj = reportPlanService.screen(dataObj);
        List<FileGroupDTO> fileGroupDTOS= new ArrayList<>();
        List<DiskFile> diskFiles = diskFileMapper.selectAll();
        for (DiskFile diskFile : diskFiles) {
            if (diskFile.getIsDir()==1&&diskFile.getParentId()==0){
                FileGroupDTO fileGroupDTO = new FileGroupDTO();
                int i = this.countFilesInFolder(diskFiles, diskFile.getId());
                fileGroupDTO.setFileCount(i);
                fileGroupDTO.setFileType(diskFile.getFileName());
                fileGroupDTOS.add(fileGroupDTO);
            }
        }


        DataObj.LearningMaterialsStatus learningMaterialsStatus = new DataObj.LearningMaterialsStatus();
        learningMaterialsStatus.setTableData(fileGroupDTOS);
        dataObj.setLearningMaterialsStatus(learningMaterialsStatus);
        return AjaxResult.success(dataObj);
    }
    public  int countFilesInFolder(List<DiskFile> files, long folderId) {
        int fileCount = 0;

        for (DiskFile file : files) {
            if (file.getParentId() == folderId) {
                if (file.getIsDir()==1) {
                    fileCount += countFilesInFolder(files, file.getId()); // 子文件夹的文件数量
                } else {
                    fileCount++; // 直接文件
                }
            }
        }
        return fileCount;
    }
    @GetMapping("getRefineryAllocations")
    public AjaxResult getRefineryAllocations() {
        List<RefineryAllocation> refineryAllocations = reportPlanService.getRefineryAllocations();
        return AjaxResult.success(refineryAllocations);
    }

    @GetMapping("examScoreStatistics")
    public AjaxResult examScoreStatistics() {
        List<ExamScoreStatistics> examScoreStatistics = reportPlanService.getExamScoreStatistics();
        return AjaxResult.success(examScoreStatistics);
    }

    @GetMapping("tankChart")
    public AjaxResult tankChart() {
        ArrayList<TankDto> tankDtos = new ArrayList<>();
        TankDto tankDto = new TankDto();
        tankDto.setName("林芝");
        BigDecimal linzhi = oilTankMapper.getTotalWeightByDeptId(107l);
        tankDto.setValue(linzhi);
        tankDtos.add(tankDto);


        BigDecimal peisong = oilTankMapper.getTotalWeightByDeptId(111l);
        TankDto tankDto1 = new TankDto();
        tankDto1.setName("配送中心");
        tankDto1.setValue(peisong);
        tankDtos.add(tankDto1);


        BigDecimal ali = oilTankMapper.getTotalWeightByDeptId(108l);
        TankDto tankDto2 = new TankDto();
        tankDto2.setName("阿里");
        tankDto2.setValue(ali);
        tankDtos.add(tankDto2);

        BigDecimal lasa = oilTankMapper.getTotalWeightByDeptId(110l);
        TankDto tankDto3 = new TankDto();
        tankDto3.setName("拉萨");
        tankDto3.setValue(lasa);
        tankDtos.add(tankDto3);

        BigDecimal rikaze = oilTankMapper.getTotalWeightByDeptId(109l);
        TankDto tankDto4 = new TankDto();
        tankDto4.setName("日喀则");
        tankDto4.setValue(rikaze);

        tankDtos.add(tankDto4);


        return AjaxResult.success(tankDtos);
    }

    /**
     * 导出采购计划列表
     */
    @PreAuthorize("@ss.hasPermi('plan:plan:export')")
    @Log(title = "采购计划", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ReportPlan reportPlan) {
        List<SysUser> sysUsers = userMapper.selectUserList(new SysUser());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<ReportPlan> list = reportPlanService.selectReportPlanList(reportPlan);
        for (ReportPlan plan : list) {
            Long id = plan.getId();
            SysUser correspondingWork = sysUsers.stream()
                    .filter(user -> user.getUserId().equals(plan.getWorkUserId()))
                    .findFirst()
                    .orElse(null);
            plan.setWorkName(ObjectUtil.isNotEmpty(correspondingWork) ? correspondingWork.getUserName() : "");


            SysUser correspondingReport = sysUsers.stream()
                    .filter(user -> user.getUserId().equals(plan.getReportUserId()))
                    .findFirst()
                    .orElse(null);
            plan.setReportName(ObjectUtil.isNotEmpty(correspondingReport) ? correspondingReport.getUserName() : "");


            // 查询 planId 对应的在途油信息
            ReportOnway reportOnway = new ReportOnway();
            reportOnway.setPlanId(id);
            List<ReportOnway> reportOnways = reportOnwayMapper.selectReportOnwayList(reportOnway);

            // 按 refineryId 对 ReportOnway 进行分组
            Map<Long, List<ReportOnway>> longListMap = this.groupByRefineryId(reportOnways);

            // 用 StringBuilder 替代 String 数组以便拼接消息
            StringBuilder msg = new StringBuilder();

            // 遍历分组，生成汇总消息
            longListMap.forEach((refineryId, reportList) -> {
                ReportRefineryInfo reportRefineryInfo = refineryInfoMapper.selectReportRefineryInfoById(refineryId);

                int i = 1;
                for (ReportOnway onway : reportList) {
                    String status = "";
                    Integer extra1 = onway.getExtra1();
                    if (extra1 == 1) {
                        status = "未到站";
                    } else if (extra1 == 2) {
                        status = "已到站";
                    } else {
                        status = "已收油" + onway.getSendWeight() + "吨";
                    }
                    msg.append(reportRefineryInfo.getRefineryName())
                            .append(" 炼厂第" + i + "批次于" + dateFormat.format(onway.getStartTime()) + "发了" + onway.getSendCarCount() + "车," + onway.getSendWeight()
                                    + "吨,预计" + dateFormat.format(onway.getArriveTime()) + "时间到达," + status + "。");
                    i++;

                }
                // 拼接汇总消息

            });

            plan.setExtra2(msg.toString());
        }

        ExcelUtil<ReportPlan> util = new ExcelUtil<ReportPlan>(ReportPlan.class);
        util.exportExcel(response, list, "采购计划数据");
    }

    /**
     * 获取采购计划详细信息
     */
    @PreAuthorize("@ss.hasPermi('plan:plan:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        ReportPlan reportPlan = reportPlanService.selectReportPlanById(id);
        return AjaxResult.success(reportPlan);
    }

    /**
     * 新增采购计划
     */
    @PreAuthorize("@ss.hasPermi('plan:plan:add')")
    @Log(title = "采购计划", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ReportPlan reportPlan) {
        //查询当月采购计划数量
        int i = reportPlanService.countCurrentMonthPlans();
        if (i > 0) {
            // throw new RuntimeException("当月已有采购计划,请前往修改");
        }
        return toAjax(reportPlanService.insertReportPlan(reportPlan));
    }
//public Boolean check(){
//
//}

    /**
     * 修改采购计划
     */
    @PreAuthorize("@ss.hasPermi('plan:plan:edit')")
    @Log(title = "采购计划", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ReportPlan reportPlan) {
        return toAjax(reportPlanService.updateReportPlan(reportPlan));
    }

    /**
     * 删除采购计划
     */
    @PreAuthorize("@ss.hasPermi('plan:plan:remove')")
    @Log(title = "采购计划", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(reportPlanService.deleteReportPlanByIds(ids));
    }
}
